# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
import os
from itemadapter import ItemAdapter


class DoubanMoviesPipeline:
    def process_item(self, item, spider):
        return item

class CSVPipeline:
    file = None

    def open_spider(self, spider): #爬虫开始时执行
        file_name = "movies.csv"
        if os.path.exists(file_name):
            os.remove(file_name)
        self.file = open(file_name, "a", encoding = "utf-8-sig")
        self.file.write("title,rate,directors,actors\n")

    def process_item(self, item, spider):
        self.file.write("{},{},\"{}\",\"{}\"\n".format(
            item["title"],
            item["rate"],
            item["directors"],
            item["actors"]
        ))

        return item

    def close_spider(self, spider): #爬虫结束时执行
        self.file.close()
